<template>
  <div>
    <el-dialog
      v-model="dialogVisibleFlag"
      :title="props.isShareEditor == '0' ? '股东添加' : '股东修改'"
      width="80%"
      @close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form :model="listQueryData">
        <el-form-item label="搜索关键字" prop="keyword">
          <el-input
            class="!w-[300px]"
            v-model="listQueryData.keyword"
            placeholder="请输入企业名称或统一社会信用代码 "
            autocomplete="off"
            clearable
          />
          <div class="ml10">
            <el-button
              type="primary"
              :disabled="!listQueryData.keyword"
              @click="hanlderShareholderInfo"
              >一键录入股东信息</el-button
            >
          </div>
        </el-form-item>
      </el-form>
      <div>
        <el-form :inline="true" :model="formList" ref="formRef" :rules="rules">
          <div v-for="(item, index) in formList.list" :key="index">
            <el-row>
              <el-col :span="6">
                <el-form-item
                  label="股东名称"
                  :prop="`list[${index}].fund_ratio`"
                  :rules="rules.fund_ratio"
                >
                  <el-input
                    v-if="item.type == 1"
                    disabled
                    placeholder="请输入股东名称"
                    v-model="item.peo_name"
                    clearable
                    @change="
                      validateNumber(item.peo_name, index, item, 'fund_ratio')
                    "
                  />
                  <el-input
                    v-else-if="item.type == 2"
                    disabled
                    placeholder="请输入股东名称"
                    v-model="item.com_name"
                    clearable
                    @change="
                      validateNumber(item.com_name, index, item, 'fund_ratio')
                    "
                  />
                  <el-input
                    v-else
                    disabled
                    placeholder="请输入股东名称"
                    v-model="item.peo_id"
                    clearable
                    @change="
                      validateNumber(item.peo_id, index, item, 'fund_ratio')
                    "
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="出资比例"
                  :prop="`list[${index}].fund_ratio`"
                  :rules="rules.fund_ratio"
                >
                  <el-input
                    disabled
                    placeholder="请输入出资比例"
                    v-model="item.fund_ratio"
                    clearable
                    @change="
                      validateNumber(item.fund_ratio, index, item, 'fund_ratio')
                    "
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="认缴日期"
                  style="width: 240px"
                  :prop="`list[${index}].subscribe_time`"
                  :rules="rules.subscribe_time"
                >
                  <el-date-picker
                    disabled
                    style="width: 300px"
                    v-model="item.subscribe_time"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择企业成立时间"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="认缴金额(万元)"
                  :prop="`list[${index}].subscribe_money`"
                  :rules="rules.subscribe_money"
                >
                  <el-input
                    disabled
                    placeholder="请输入认缴出资金额(万元)
                "
                    v-model="item.subscribe_money"
                    clearable
                    @change="
                      validateNumber(
                        item.subscribe_money,
                        index,
                        item,
                        'subscribe_money'
                      )
                    "
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="实缴金额(万元)"
                  :prop="`list[${index}].practical_money`"
                  :rules="rules.practical_money"
                >
                  <el-input
                    disabled
                    placeholder="请输入实缴出资金额(万元)
                          "
                    v-model="item.practical_money"
                    clearable
                    @change="
                      validateNumber(
                        item.practical_money,
                        index,
                        item,
                        'practical_money'
                      )
                    "
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="持股比例"
                  :prop="`list[${index}].shareholding_ratio`"
                >
                  <el-input
                    :disabled="item.isDisadled"
                    placeholder="请输入持股比例"
                    v-model="item.shareholding_ratio"
                    clearable
                    @change="
                      validateNumber(
                        item.shareholding_ratio,
                        index,
                        item,
                        'shareholding_ratio'
                      )
                    "
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="受益股份"
                  :prop="`list[${index}].shareholding_beneficial`"
                >
                  <el-input
                    :disabled="item.isDisadled"
                    placeholder="请输入终受益股份比例
                          "
                    v-model="item.shareholding_beneficial"
                    clearable
                    @change="
                      validateNumber(
                        item.shareholding_beneficial,
                        index,
                        item,
                        'shareholding_beneficial'
                      )
                    "
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <!-- <el-button type="primary" @click="handleAdd">新增</el-button> -->
                <!-- <el-button
                  type="success"
                  @click="addCompanyShareInsert(item, index)"
                >
                  提交
                </el-button> -->
                <!-- <el-button
                  type="primary"
                  v-if="gudongId"
                  :icon="useRenderIcon(EditPen)"
                  circle
                  @click="handleEdit(item, index)"
                />
                <el-button
                  type="danger"
                  :icon="useRenderIcon(Delete)"
                  icon="el-icon-delete"
                  circle
                  @click="handleDelete(index)"
                /> -->
              </el-col>
            </el-row>
          </div>
          <div class="add-box">
            <el-button @click="addCompanyShareInsert(formList)" type="primary">
              提交
            </el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { getSessionKey } from "@/utils/auth";
import Refresh from "@iconify-icons/ep/refresh";
import Delete from "@iconify-icons/ep/delete";
import EditPen from "@iconify-icons/ep/edit-pen";
import Search from "@iconify-icons/ep/search";
import Check from "@iconify-icons/ep/check";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { message } from "@/utils/message";
// import {
//   peopleSelect,
//   companyShareInsert,
//   companyShareUpdate,
//   gudong
// } from "@/api/companyList";
import {
  peopleSelect,
  // companyShareInsert,
  companyShareUpdate,
  companyInsert,
  gudong,
  gongsi,
  shareInsert
} from "@/api/companyList";
import { peopleInsert } from "@/api/personnelPage";

import {
  reactive,
  ref,
  inject,
  onMounted,
  defineProps,
  defineEmits,
  nextTick,
  defineExpose,
  watch
} from "vue";
import { fa, id } from "element-plus/es/locale";
import { json } from "stream/consumers";
import { List } from "echarts/core";
import { any } from "vue-types";
import { number } from "echarts";
const gudongId = ref("");
const dialogVisibleFlag = ref(false);
const listQuery = ref({});
const listQueryRef = ref("");
const formRef = ref("");
const keyword = ref("");
const companyIdInfo = ref();

const props = defineProps({
  isShareEditor: {
    type: String,
    default: ""
  }
});
const listQueryData = reactive({
  keyword: ""
});
const rules = ref({
  people_id: [{ required: true, message: "请选择人员", trigger: "blur" }],
  fund_ratio: [{ required: true, message: "请输入出资比例", trigger: "blur" }],
  subscribe_time: [
    { required: true, message: "请选择认缴出资日期", trigger: "blur" }
  ],
  subscribe_money: [
    { required: true, message: "请输入认缴出资金额", trigger: "blur" }
  ],
  practical_money: [
    { required: true, message: "请输入实缴出资金额", trigger: "blur" }
  ],
  shareholding_ratio: [
    { required: true, message: "请输入持股比例", trigger: "blur" }
  ],
  shareholding_beneficial: [
    { required: true, message: "最终受益股份比例", trigger: "blur" }
  ]
});
onMounted(() => {
  getList();
});

const isUpOrAdd = ref(false);
// 添加
const hanlderShareholderInfo = () => {
  const params = {
    keyword: listQueryData.keyword
  };
  isUpOrAdd.value = true;
  gudong(params).then(res => {
    console.log(res, "参数的哈哈哈哈哈好");
    if (res.code == 200) {
      // isFlag.value = true;
      formList.value.list = res.data;
    } else {
      // isFlag.value = false;
    }
  });
};

// 打开弹框
const openShareEditorDialog = row => {
  console.log(row, "rowrowrow");
  dialogVisibleFlag.value = true;
  formList.value.list = row.shareholder_array;
  companyIdInfo.value = row.id;
};
// 提交

const getList = async () => {
  const obj = {
    name: ""
  };
  const res = await peopleSelect(obj);
  if (res.code == 200) {
    const dataList = res.data;
    optionsList.value = dataList;
  }
};
const handleDelete = index => {
  if (formList.value.list.length == 1) {
    message("暂无法删除", { type: "error" });
    return;
  }
  formList.value.list.splice(index, 1);
};
const optionsList = ref([]);
const formList = ref({
  list: [
    {
      people_id: "",
      fund_ratio: "",
      subscribe_time: "",
      subscribe_money: "",
      practical_money: "",
      shareholding_ratio: "",
      shareholding_beneficial: "",
      company_id: "",
      type: "",
      peo_name: "",
      com_name: ""
    }
  ]
});
// 格式化
const validateNumber = (value, index, el, name) => {
  let newValue = value;

  const elInfo = JSON.parse(JSON.stringify(el));
  if (newValue) {
    newValue = newValue.toString();
    newValue = newValue.replace(/[^0-9.]/g, ""); ////清除"数字"和"."以外的字符
    newValue = newValue.replace(/^\./g, ""); //验证第一个字符是数字而不是点
    newValue = newValue.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的点
    newValue = newValue
      .replace(".", "$#$")
      .replace(/\./g, "")
      .replace("$#$", "."); //只保留第一个. 清除多余的点
    newValue = newValue.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能输入两个小数
    newValue = Number(newValue);

    elInfo[name] = newValue;
    formList.value.list[index][name] = elInfo[name];
  }
};

// 编辑
// const handleEdit = (item, i) => {
//   formList.value.list.map((el, index) => {
//     if (i == index) {
//       el.isDisadled = false;
//     }
//   });
// };
// 添加
// const handleAdd = () => {
//   formList.value.list.push({
//     people_id: "",
//     fund_ratio: "",
//     subscribe_time: "",
//     subscribe_money: "",
//     practical_money: "",
//     shareholding_ratio: "",
//     shareholding_beneficial: "",
//     company_id: ""
//   });
// };
// 股东保存提交按钮
const emit = defineEmits(["handleshareEditor"]);
const addCompanyShareInsert = (item, i) => {
  // console.log(item.list);

  formRef.value.validate(valid => {
    if (valid) {
      if (isUpOrAdd.value) {
        console.log("添加");
        const listArr = JSON.parse(JSON.stringify(formList.value.list));
        listArr.map(el => {
          // console.log(el, "===-----====");
          if (el.peo_id.includes("公司") || el.peo_id.length > 4) {
            // console.log(el.peo_id, "公司");
            getGoingsi(el.peo_id);
          } else {
            // console.log(el.peo_id, "个人");
            getPeopleInsert(el.peo_id);
          }
        });
        setTimeout(() => {
          const itemData = JSON.parse(JSON.stringify(formList.value.list));
          console.log(itemData);
          const params = {
            action: "update",
            company_id: companyIdInfo.value,
            value: JSON.stringify(formList.value.list)
          };
          console.log(params, "itemData", formList.value.list);

          companyShareUpdate(params).then(res => {
            if (res.code == 200) {
              message(res.msg, { type: "success" });
              handleClose();
              emit("handleshareEditor");
            }
          });
        }, 500);
      } else {
        console.log("编辑");
        const itemData = JSON.parse(JSON.stringify(item.list));
        const newList = [];
        itemData.map(el => {
          newList.push({
            id: el.id,
            company_id: el.company_id,
            peo_id: el.peo_id,
            com_id: el.com_id,
            type: el.type,
            fund_ratio: el.fund_ratio,
            subscribe_time: el.subscribe_time,
            subscribe_money: el.subscribe_money,
            practical_money: el.practical_money,
            shareholding_ratio: el.shareholding_ratio,
            shareholding_beneficial: el.shareholding_beneficial
          });
        });
        const obj = reactive({
          action: "xiugai",
          company_id: any,
          value: JSON.stringify(newList)
        });
        console.log(obj);
        companyShareUpdate(obj).then(res => {
          if (res.code == 200) {
            message(res.msg, { type: "success" });
            handleClose();
            emit("handleshareEditor");
          }
        });
      }
    } else {
      return false;
    }
  });
};

// 人员绑定
const getPeopleInsert = async name => {
  const obj = {
    admin_id: getSessionKey().admin_id,
    name,
    status: 1
  };
  const res = await peopleInsert(obj);
  const formListInfo = JSON.parse(JSON.stringify(formList.value.list));
  const infoList = [];
  formListInfo.filter(el => {
    if (el.peo_id == name) {
      el.peo_id = res.data;
      infoList.push({
        peo_id: name,
        id: res.data
      });
    }
    return el;
  });
  const arrData = infoList.map(el => {
    formList.value.list.map(item => {
      if (el.peo_id == item.peo_id) {
        item.peo_id = el.id;
        item.company_id = companyIdInfo.value;
        item.type = 1;
      }
    });
    return el;
  });
};

// 公司绑定
const getGoingsi = async keyword => {
  const params = {
    keyword
  };
  const resinfo = await gongsi(params);
  console.log(resinfo, "resinfo");
  const tax_code = resinfo.data.tax_code;
  // 人员添加
  const info = {
    admin_id: getSessionKey().admin_id,
    name: resinfo.data.legal,
    status: 1
  };
  const res = await peopleInsert(info);
  const obj = {
    name: keyword,
    ...resinfo.data,
    legal: res.data,
    admin_id: getSessionKey().admin_id
  };
  const res1 = await companyInsert(obj);
  const comId = res1.data;
  const formListInfoData = JSON.parse(JSON.stringify(formList.value.list));
  const arr = [];
  console.log("参数的", formListInfoData);
  formListInfoData.map(el => {
    if (el.peo_id.length > 3) {
      arr.push({
        peo_id: el.peo_id,
        comId
      });
    }
    return el;
  });
  arr.map(el => {
    formList.value.list.map(item => {
      if (el.peo_id == item.peo_id) {
        item.com_id = comId;
        item.type = 2;
        item.company_id = companyIdInfo.value;
        delete item.peo_id;
      }
    });
    return el;
  });
  // const inFo = JSON.parse(JSON.stringify(formList.value.list));
  // const params = {
  //   value: JSON.stringify(inFo)
  // };
  // shareInsert(params).then(res => {
  //   if (res.code == 200) {
  //     message(res.msg, { type: "success" });
  //     // closeShareEditorDialog();
  //   }
  // });
};

const closeShareEditorDialog = () => {
  listQueryData.keyword = "";
  dialogVisibleFlag.value = false;
  // isFlag.value = false;
  formList.value.list = [];
};
const handleClose = () => {
  formList.value.list = [];
  listQueryData.keyword = "";
  isUpOrAdd.value = false;
  dialogVisibleFlag.value = false;
};
defineExpose({ openShareEditorDialog, handleClose });

const handleSubmit = () => {
  listQueryRef.value.validate(valid => {
    if (valid) {
      // 添加
      const parmas = listQuery.value;
      // parmas.admin_id = getSessionKey().admin_id;
      emit("handleSubmit", parmas);
    }
  });
};
</script>

<style lang="scss" scoped></style>
